package com.xiaow.springsecuriydemo.service.impl;

import com.xiaow.springsecuriydemo.entity.User;
import com.xiaow.springsecuriydemo.service.LoginService;
import com.xiaow.springsecuriydemo.utils.JwtUtils;
import com.xiaow.springsecuriydemo.vo.LoginUser;
import com.xiaow.springsecuriydemo.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Objects;

/**
 * @ClassName LoginServiceImpl
 * @Author xiaow
 * @DATE 2022/9/15 10:16
 **/
@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result login(User user) {
//        用户认证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
//        这里就会跳到loginservice中进行密码和账户的比对
//        loginservice中只会拿到用户的信息并判断是否有这个用户，使用userDetailService进行查询用户密码，然后再由springsecurity内部的内容进行比对密码，这就是我们设置密码加密器和重写userdetail的原因
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
//        认证通过了
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        User user1 = principal.getUser();
        Long id = user1.getId();
        String jwt = JwtUtils.generateAdminJsonWebToken(id.toString());
        System.out.println(jwt);
//        向redis中存储信息
        redisTemplate.opsForValue().set("login" + id, user1);
        return Result.succ(jwt);
    }

    @Override
    public Result logout() {
//        获取SecurityHolder中的信息，并删除对应用户
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
//删除redis中值
        redisTemplate.delete("login" + id);
        return Result.succ("退出成功");
    }
}
